//
//  SIHomeViewController.swift
//  SinaImiate
//
//  Created by xiaoming on 16/6/29.
//  Copyright © 2016年 GoodJob. All rights reserved.
//

import UIKit

private let originalCellId = "originalCellId"
private let retransmissionCellId = "retransmissionCellId"

class SIHomeViewController: SIBaseViewController {
    
    private lazy var listViewModel = SIStatusListViewModel()
    

    override func viewDidLoad() {
        super.viewDidLoad()
        
        NotificationCenter.default.addObserver(self, selector: #selector(browserPhoto), name: NSNotification.Name(rawValue: SIStatusCellBrowserPhotoNotification), object: nil)
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    @objc private func browserPhoto(n: Notification) {
        
        guard let selectedIndex = n.userInfo?[SIStatusCellBrowserPhotoSelectedIndexKey] as? Int,
            urls = n.userInfo?[SIStatusCellBrowserPhotoURLsKey] as? [String],
            imageViewList = n.userInfo?[SIStatusCellBrowserPhotoImageViewsKey] as? [UIImageView]
            else {
            return
        }
        
        let vc = HMPhotoBrowserController.photoBrowser(withSelectedIndex: selectedIndex, urls: urls, parentImageViews: imageViewList)
        
        present(vc, animated: true, completion: nil)
        
    }

    @objc private func showFriends() {
        
        let vc = SIDemoViewController()
        
        navigationController?.pushViewController(vc, animated: true)
    }
    
    override func loadData() {
        
//        listViewModel.loadStatus(pullup: isPullup) { (isSuccess, shouldRefresh) in
//            
//            print("加载完成")
//            
//            self.refreshControl?.endRefreshing()
//            
//            self.isPullup = false
//            
//            ///需要刷新数据时候刷新
//            if shouldRefresh {
//                
//                self.tableview?.reloadData()
//            }
//            
//        }
        print("准备刷新")
        
        refreshControl?.beginRefreshing()
        
        DispatchQueue.main.after(when: DispatchTime.now() + 1) {
            self.listViewModel.loadStatus(pullup: self.isPullup, completion: { (isSuccess, shouldRefresh) in
                
                print("加载数据结束")
                
                self.refreshControl?.endRefreshing()
                
                self.isPullup = false
                
                if shouldRefresh  {
                    
                    self.tableview?.reloadData()
                }
                
            })
        }
    }
        
    
}

extension SIHomeViewController {
    
    //FIXME: interval什么意思 -> 内部的,没有什么用
    override func setupTableView() {

        super.setupTableView()
        
        view.backgroundColor = UIColor.brown()
        
        navItem.leftBarButtonItem = UIBarButtonItem(title: "好友", fontSize: 16, target: self, action: #selector(showFriends))
        
        tableview?.register(UINib(nibName: "SIStatusCell", bundle: nil), forCellReuseIdentifier: originalCellId)
        tableview?.register(UINib(nibName: "SIStatusRetransmissionCell", bundle: nil), forCellReuseIdentifier: retransmissionCellId)
        //取消自动行高
//        tableview?.rowHeight = UITableViewAutomaticDimension
        tableview?.estimatedRowHeight = 200
        
        setupNavTitle()
    }
    
    private func setupNavTitle() {
        
        let title = SINetworkTools.shared.userAccount.screen_name
        
        let button = SITitleButton(title: title)
        navItem.titleView = button
        
        button.addTarget(self, action: #selector(clickTitle), for: .touchUpInside)
        
    }
    
    @objc func clickTitle(btn: UIButton) {
        
        btn.isSelected = !btn.isSelected
    }
}

extension SIHomeViewController {
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return listViewModel.statusList.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let viewModel = listViewModel.statusList[indexPath.row]
        
        let cellId = (viewModel.status.retweeted_status != nil) ? retransmissionCellId : originalCellId
        
        //如果没有, 找到cell, 按照自动布局的规划, 从上向下计算, 找到向下的约束, 从而计算动态行高
        let cell = tableview?.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! SIStatusCell
        
        
        cell.viewModel = viewModel
        cell.delegate = self
        
        
        return cell
    }
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        let vm = listViewModel.statusList[indexPath.row]
        
        return vm.rowHeight
    }
}

// MARK: - cell的协议方法
extension SIHomeViewController: SIStatusCellDelegate {
    
    func statusCellDidSelectedUrlString(cell: SIStatusCell, urlString: String) {
        
//        print(urlString) 
        let vc = SIWebViewController()
        
        vc.urlString = urlString
        
        navigationController?.pushViewController(vc, animated: true)
        
    }
    
}

